﻿using Furion.DatabaseAccessor.Extensions;
using Furion.LinqBuilder;
using Furion.Localization;
using ST.Torch.WebApi.Application.AOP;
using ST.Torch.WebApi.Application.System.Dtos;
using ST.Torch.WebApi.Application.System.Services;
using ST.Torch.WebApi.Application.Utils.Services;
using ST.Torch.WebApi.Core.Entities.System;
using Microsoft.AspNetCore.Mvc.Filters;
using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace ST.Torch.WebApi.Application.System
{

    /// <summary>
    /// 系统服务接口
    /// </summary>
    [AppAuthorize]
    //[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
    public class SYSUserAppService : IDynamicApiController
	{
       

        private readonly SYSUserService _SYSUserService;
		private readonly SYSRoleService _SYSRoleService;
        private readonly IUIDService _UIDService;


        public SYSUserAppService(SYSUserService SYSUserService, SYSRoleService SYSRoleService, IUIDService uIDService
            )
		{
			_SYSUserService = SYSUserService;
            _SYSRoleService = SYSRoleService;
            _UIDService = uIDService;
        }

       
        [HttpPost]
		public async Task<PagedList<SYSUserListDto>> GetUserPagedList([FromForm] PageReq req)
		{
            Expression<Func<SYSUser, bool>> predicate = u => true;
            predicate=predicate.AndIf(!string.IsNullOrEmpty(req.key),u=>u.Account.Contains(req.key) || u.NickName.Contains(req.key));
			var dataList= await _SYSUserService.QueryPageAsync(predicate, req);
            PagedList<SYSUserListDto> resultList = dataList.Adapt<PagedList<SYSUserListDto>>();

			return resultList;
		}
        [HttpPost]
        public async Task<SYSUserListDto> Single([FromForm] Guid Id)
        {
           
           var entity= await _SYSUserService.SingleAsync(u=>u.Id==Id);
            SYSUserListDto resultData = entity.Adapt<SYSUserListDto>();
			return resultData;

        }
        
        [HttpPost]
        [OperateAuth("AddUserPage")]
        public async Task  Insert([FromForm] SYSUserDto model)
		{
			SYSUser entity = model.Adapt<SYSUser>();
			var IsExist = await _SYSUserService.AnyAsync(u => u.Account == model.Account);

            if (IsExist)
			{
				
                throw Oops.Oh($"{model.Account} "+L.Text["账号已存在"]);
            }
            entity.Password = entity.GetPassEncryption("000000");
            await _SYSUserService.InsertAsync(entity);
		}
		[HttpPost]
        [OperateAuth("EditUserPage")]
        public async Task Update([FromForm] SYSUserListDto model)
		{
			
			var entity=await _SYSUserService.SingleAsync(u => u.Id == model.Id);
			entity.NickName=model.NickName;
			entity.Sex=model.Sex;
			entity.Contact=model.Contact;
			entity.Img=model.Img;
			entity.IsEnable=model.IsEnable;
            entity.UpdateTime=DateTime.Now;
			await _SYSUserService.UpdateAsync(entity);
		}

        [HttpPost]
        [OperateAuth("EditUserPage")]
        public async Task UpdatePassword([FromForm] Guid Id, [FromForm] string OldPass, [FromForm] string NewPass)
        {
            
            var entity = await _SYSUserService.SingleAsync(u => u.Id == Id);
            if(entity.GetPassEncryption(OldPass) != entity.Password)
            {
                throw Oops.Oh(L.Text["输入旧密码不对"]);
            }
            entity.Password= entity.GetPassEncryption(NewPass);
            await _SYSUserService.UpdateAsync(entity);
        }


        [HttpPost]
        [OperateAuth("DelUserPage")]
        public async Task DeleteAsync([FromForm] Guid Id)
		{
			var entity = await _SYSUserService.SingleAsync(u => u.Id == Id);
			await _SYSUserService.DeleteAsync(entity,true);
		}
        [HttpPost]
        [OperateAuth("DelUserPage")]
        public async Task DeleteBatchAsync([FromForm] List<Guid> Ids)
        {
            var entitys = await _SYSUserService.QueryAsync(u => Ids.Contains(u.Id));
            foreach (var entity in entitys)
            {
                await _SYSUserService.DeleteAsync(entity, true);
            }

        }
        [HttpPost]
        [OperateAuth("EditUserPage")]
        public async Task UpdateIsEnable([FromForm] Guid Id, [FromForm] bool IsEnable)
        {

            var entity = await _SYSUserService.SingleAsync(u => u.Id == Id);
            entity.IsEnable = IsEnable;
            entity.UpdateTime = DateTime.Now;
            await _SYSUserService.UpdateAsync(entity);
        }
        [HttpPost]
        [OperateAuth("EditUserPage")]
        public async Task ResetPassword([FromForm] Guid Id)
        {

            var entity = await _SYSUserService.SingleAsync(u => u.Id == Id);
            entity.Password = entity.GetPassEncryption("000000");
            entity.UpdateTime = DateTime.Now;
            await _SYSUserService.UpdateAsync(entity);
        }

        [HttpPost]
        [OperateAuth("AssignRoleUserPage")]
        public async Task InsertUserRole([FromForm] Guid UserId, [FromForm] List<Guid> RoleIds)
        {
       
            var entity = await _SYSUserService.SingleAsync(u => u.Id == UserId, true,true);
            var roles = await _SYSRoleService.QueryAsync(u => RoleIds.Contains(u.Id),false,false);
            List<SYSRole> DelR = new List<SYSRole>();
            List<SYSRole> AlreadyAddR = new List<SYSRole>();
            foreach (var item in entity.Roles)
            {
                if (roles.Any(u => u.Id == item.Id))
                {
                    AlreadyAddR.Add(item);
                }
                else
                {
                    DelR.Add(item);
                }
            }
            foreach (var item in DelR)
            {
                entity.Roles.Remove(item);
            }
            foreach (var item in roles)
            {
                if (!AlreadyAddR.Any(u => u.Id == item.Id))
                {
                    entity.Roles.Add(item);// = new List<SYSMenu>();
                }
            }

            await entity.UpdateAsync();
            await _UIDService.CleanCacheById(UserId);
            //await _UIDService.CleanAllCache();
            return;


        }

        [HttpPost]

        public async Task<List<SYSUserRoleDto>> GetUserRole([FromForm] Guid Id)
        {
            var Roles = await _SYSRoleService.QueryAsync(u => true);
            var Users = await _SYSUserService.SingleAsync(u => u.Id == Id, true);
			var Data=Roles.Select(u => new SYSUserRoleDto { id=u.Id, title=u.Name,@checked=false }).ToList();
			foreach (var item in Data)
			{
				if (Users.Roles.Any(u => u.Id == item.id))
				{
                    item.@checked = true;

                }
			}

            return Data;


        }
    }

}
